<!--
 * @Description  :
 * @Autor        : guoxi
 * @Date         : 2022-06-16 10:16:50
 * @LastEditors  : Please set LastEditors
 * @LastEditTime : 2022-09-05 14:50:03
 * @FilePath     : \rpms\src\views\project\build\detail\index.vue
-->
<template>
  <el-card>
    <div class="card-wrap">
      <el-page-header content="发起评审" @back="handleBack" />
      <div v-if="!isApproval">
        <el-button @click="goBack">取消</el-button>
        <el-button
          type="primary"
          v-if="!route.query.instanceId"
          :loading="model.saveLoading"
          @click="handleSave"
          >保存</el-button
        >
        <el-button
          type="primary"
          :loading="model.saveLoading"
          @click="model.centerDialogVisible = true"
          >发起</el-button
        >
      </div>
    </div>
  </el-card>
  <br />

  <el-form
    :model="model.formData"
    :disabled="isApproval"
    ref="formRef"
    @submit.prevent
    :rules="formRules"
    label-width="140px"
  >
    <el-card>
      <template #header>
        <div class="card-box-header">
          <span>评审发起信息</span>
          <div v-if="show2" @click="show2 = !show2" class="header-btn">
            收起
            <i class="el-icon-arrow-down"></i>
          </div>
          <div v-else @click="show2 = !show2" class="header-btn">
            展开
            <i class="el-icon-arrow-right"></i>
          </div>
        </div>
      </template>
      <div v-show="show2">
        <el-row>
          <el-col :xl="8" :lg="12">
            <el-form-item label="项目编号" prop="projectManageId">
              <el-select
                v-model="model.formData.projectManageId"
                style="width: 100%"
                filterable
                clearable
                :multiple="false"
                remote
                placeholder="请输入项目编号搜索"
                :remote-method="getProjectList"
                value-key="id"
                @change="changeHandleder"
              >
                <el-option
                  id="default-option"
                  v-for="item in model.projectList"
                  :key="item.id"
                  :label="item.projectCode"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xl="8" :lg="12">
            <el-form-item label="项目名称">
              <el-input disabled :value="model.formData.projectName"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :xl="8" :lg="12">
            <el-form-item label="评审轮次" prop="reviewRoundCode">
              <el-select
                :disabled="isApproval"
                v-model="model.formData.reviewRoundCode"
                clearable
                style="width: 100%"
                value-key="dicCode"
              >
                <el-option
                  id="default-option"
                  v-for="item in projectRounds"
                  :key="item.dicCode"
                  :label="item.dicValue"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xl="8" :lg="12">
            <el-form-item label="评审项目阶段" prop="reviewStageCode">
              <el-select
                v-model="model.formData.reviewStageCode"
                clearable
                style="width: 100%"
                value-key="dicCode"
                @change="changeeRviewStage"
              >
                <el-option
                  id="default-option"
                  v-for="item in projectStages"
                  :key="item.dicCode"
                  :label="item.dicValue"
                  :value="item"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <div v-if="model.selectProject">
          <common-info
            :projectId="model.selectProject.id"
            :reviewStageName="model.formData.reviewStageName"
          ></common-info>
        </div>

        <el-row>
          <el-col :xl="16" :lg="24">
            <el-form-item label="评审专家" prop="catchFroms">
              <SelectForTable
                ref="authorSelectTable"
                :value="model.formData.rvwUserList"
                :isUser="false"
                :isCustom="true"
                @change="changeAuthor"
              >
                <template v-slot:tableData="{ data }">
                  <el-table
                    v-if="data.length > 0"
                    :data="data"
                    border
                    :header-cell-style="{
                      background: '#eef1f6',
                      color: '#606266'
                    }"
                  >
                    <template #empty>
                      <el-empty
                        :image-size="40"
                        description="暂无数据"
                      ></el-empty>
                    </template>
                    <el-table-column type="index" label="序号" />
                    <el-table-column
                      prop="name"
                      label="专家姓名"
                    ></el-table-column>

                    <el-table-column label="所属单位">
                      <template #default="scope">
                        {{ scope.row?.companyName || scope.row?.department }}
                      </template>
                    </el-table-column>

                    <el-table-column prop="ext1" label="专家组别" />
                    <el-table-column label="专家类别">
                      <template #default="scope">
                        <el-select
                          style="width: 100%"
                          v-model="scope.row.opinion"
                          clearable
                          placeholder="请选择"
                          value-key="dicCode"
                        >
                          <el-option
                            v-for="item in expertCategoryList"
                            :key="item.dicCode"
                            :label="item.dicValue"
                            :value="item"
                          ></el-option>
                        </el-select>
                        <!-- <el-input
                        type="textarea"
                        v-model="scope.row.opinion"
                      /> -->
                      </template>
                    </el-table-column>
                  </el-table>
                </template>
              </SelectForTable>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </el-form>
  <el-dialog
    v-model="model.centerDialogVisible"
    title="发起评审"
    width="30%"
    align-center
  >
    <span
      >发起后，各位评审专家将收到待处理评审填报消息，是否确认发起评审？</span
    >
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="model.centerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import CommonInfo from "../components/commonInfo.vue";
import {
  flowStart,
  saveExpert,
  postProjectList,
  addExpert,
  getExpertDetail,
  flowSubmit
} from "/@/api/project";
import SelectForTable from "/@/components/selectForTable/index.vue";
import { cloneDeep } from "lodash-es";
import NotifMessage from "/@/utils/message/notification";
import { postDictList } from "/@/api/common";
import { storageLocal } from "/@/utils/storage";
const router = useRouter();
const route = useRoute();
// const nodeId = route.query.nodeId ? route.query.nodeId : "ACT_010";
const formRef = ref<HTMLFormElement | null>(null) as any;
let show2 = ref<boolean>(true);
const expertId = route.query.id;
let projectStages = ref([]);
let projectRounds = ref([]);
let expertCategoryList = ref([]);
const authorSelectTable = ref(null);
const formRules = ref({
  projectManageId: [
    { required: true, message: "请选择需评审的项目", trigger: "change" }
  ],
  reviewRoundCode: [
    { required: true, message: "请选择评审轮次", trigger: "change" }
  ],
  reviewStageCode: [
    { required: true, message: "请选择评审轮次", trigger: "change" }
  ],
  catchFroms: [
    { required: true, message: "请选择所需要的专家", trigger: "change" }
  ]
});
const model = reactive({
  types: [
    { key: "1", label: "新产品" },
    { key: "2", label: "新装置" },
    { key: "3", label: "新材料" },
    { key: "4", label: "新工艺/方法/模式" },
    { key: "5", label: "专利" },
    { key: "6", label: "软件著作权" },
    { key: "7", label: "论文" },
    { key: "8", label: "专著" },
    { key: "9", label: "标准" },
    { key: "10", label: "研究报告" },
    { key: "11", label: "计算机软件" },
    { key: "12", label: "技术指标" },
    { key: "13", label: "其他" }
  ],
  centerDialogVisible: false,
  selectProject: null,
  flowType: "3009",
  saveLoading: false,
  projectList: [],
  pslcArr: [],
  defaultFileList: [],
  reportDefaultFileList: [],
  recordDefaultFileList: [],
  reviewDefaultFileList: [],
  approvalDefaultFileList: [],
  evaludate: {
    memberList: [],
    evaluationTime: "",
    remark: "",
    evaluationMembers: [],
    evaluationResult: "",
    defaultFileList: [],
    evaluationReport: []
  },
  changeFormData: {
    alterationMatters: "",
    alterationReason: "",
    alterationTime: "",
    remark: ""
  },

  formData: {
    projectManageId: "",
    projectName: "",
    reviewRoundCode: null,
    reviewRoundName: "",
    reviewStageCode: null,
    reviewStageName: "",
    reviewSaveStatus: "1",
    reviewApproveStatus: "0",
    rvwUserList: [],
    catchFroms: []
  }
});
const flowPassData = reactive({
  formBaseInfo: {
    id: route.query.id,
    acceptUsers: null
  },
  flowFormData: {
    approvalComments: "",
    approvalResult: "",
    businessId: route.query.id,
    flowId: route.query.flowId,
    flowTypeCode: "",
    instanceId: route.query.instanceId,
    nodeId: route.query.nodeId,
    remarks: "",
    saveState: "1"
  },
  formSubMap: {
    stageStatus: "3009",
    flowType: "",
    nodeId: route.query.nodeId,
    procInstId: route.query.instanceId,
    taskId: route.query.taskId,
    opinion: "",
    assignee: null,
    isChargehand: "1", //1：向下提交到下一步：0：回退到某一步
    specialReject: "0"
  },
  tmpStorage: {
    nodeId: route.query.nodeId,
    flowId: route.query.flowId,
    taskId: route.query.taskId,
    handlerId: null,
    valueJson: ""
  }
});

const flowStartData = reactive({
  formBaseInfo: {
    billName: "",
    projectName: "",
    projectManageId: null,
    id: route.query.id,
    flowStartAttachmentArr: []
  },
  flowFormData: {
    businessId: route.query.id,
    flowTypeCode: "3009",
    nodeId: null,
    projectManageId: null,
    remarks: "",
    saveState: "1"
  },
  formSubMap: {
    stageStatus: "3009", //立项：2，变更：20，验收：4
    flowType: "3009",
    assignee: null,
    opinion: ""
  }
});

const flowPassSubmit = async () => {
  flowPassData.flowFormData.approvalComments = "";
  flowPassData.flowFormData.approvalResult = "1"; //同意：1，不同意：0
  flowPassData.flowFormData.remarks = "";
  flowPassData.flowFormData.flowTypeCode = model.flowType;
  flowPassData.formSubMap.opinion = ``;
  flowPassData.tmpStorage.valueJson = JSON.stringify(flowPassData.formSubMap);
  const info = storageLocal.getItem("rdms-info");
  const userId = info?.userId;
  flowPassData.tmpStorage.handlerId = userId;
  const assignee = model.formData.rvwUserList.map(el => el.userId);
  flowPassData.formBaseInfo.acceptUsers = assignee.join(",");
  flowPassData.formSubMap.assignee = assignee.join(",");
  flowPassData.formSubMap.isChargehand = "1";
  flowPassData.formSubMap.flowType = model.flowType;
  const { code, message } = await flowSubmit(flowPassData);
  if (code === 200) {
    NotifMessage.success(message);
    router.push("/approval/todo");
  } else {
    model.saveLoading = false;
    model.centerDialogVisible = false;
    NotifMessage.error(message);
  }
};

const changeAuthor = item => {
  model.formData.catchFroms = item;
};

const initPslcList = async () => {
  try {
    const params = {
      dicType: "rd_principal_cmpy"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      model.pslcArr = data;
    }
  } catch (err) {
    console.log(err);
  }
};

const getProjectList = async (query = "") => {
  // if (!query) {
  //   model.projectList = [];
  //   return;
  // }
  try {
    const params = {
      pageNum: 1,
      pageSize: 0,
      projectCodeLike: query
    };
    const { code, data } = await postProjectList(params);
    if (code === 200) {
      model.projectList = data.list;
    }
  } catch (err) {
    console.log(err);
  }
};

// const getProjectFroms = async id => {
//   const { code, data } = await getProjectInfo({ id });
//   if (code === 200) {
//     // model.selectProject = data;
//     const copyFormData = cloneDeep(data);
//     projectInfo.value = copyFormData;
//     if (copyFormData.projectFsbStudyDTO) {
//       defaultFileList.value =
//         copyFormData.projectFsbStudyDTO.fsbStudyAttachmentArr;
//       defaultFileList.value.map(el => {
//         el["name"] = el.fileName;
//       });
//     } else {
//       defaultFileList.value = [];
//     }
//     if (copyFormData.projectProposalArr) {
//       defaultProposaFileList.value = copyFormData.projectProposalArr;
//       defaultProposaFileList.value.map(el => {
//         el["name"] = el.fileName;
//       });
//     } else {
//       defaultProposaFileList.value = [];
//     }

//     if (copyFormData.projectPlans) {
//       tableData.value = copyFormData.projectPlans.map(el => {
//         return {
//           time: el.startTime.split(" ")[0] + "至" + el.endTime.split(" ")[0],
//           timeObj: [el.startTime.split(" ")[0], el.endTime.split(" ")[0]],
//           content: el.researchContent,
//           goal: el.goal,
//           isDone: el.done,
//           doneDes: el.doneDes,
//           doneTime: el.doneTime,
//           attachment: (el.attachment && JSON.parse(el.attachment)) || []
//         };
//       });
//     }

//     const res = await getAacceptanceById(id);
//     if (res.data.finaReportAttachmentArr) {
//       model.approvalDefaultFileList = res.data.finaReportAttachmentArr;
//       model.approvalDefaultFileList.map(el => {
//         el["name"] = el.fileName;
//       });
//     }

//     if (res.data.accReportAttachmentArr) {
//       model.reviewDefaultFileList = res.data.accReportAttachmentArr;
//       model.reviewDefaultFileList.map(el => {
//         el["name"] = el.fileName;
//       });
//     }
//     if (res.data.projectTargetList) {
//       res.data.projectTargetList.map(el => {
//         if (el.scientificAchv) {
//           const strArr = el.scientificAchv.split(",");
//           el.scientificAchv = strArr.map(str => +str);
//         }
//         if (el.scientificAchvs) {
//           el.scientificAchvs.map(obj => {
//             if (obj.kyAttachmentArr == null) {
//               obj.kyAttachmentArr = [];
//             } else {
//               obj.kyAttachmentArr.map(file => {
//                 file["name"] = file.fileName;
//               });
//             }
//           });
//         }
//       });
//       checkTableData.value = res.data.projectTargetList;
//     }

//     const res2 = await getEvaluationById(id);
//     if (res2.code === 200 && res2.data != null) {
//       model.evaludate = res2.data;

//       model.evaludate.evaluationMembers == null
//         ? []
//         : (model.evaludate.evaluationMembers = JSON.parse(
//             res2.data.evaluationMembers
//           ));
//       if (
//         model.evaludate.evaluationReport &&
//         model.evaludate.evaluationReport.indexOf("{") !== -1
//       ) {
//         model.evaludate.evaluationReport = JSON.parse(
//           res2.data.evaluationReport
//         );
//         model.evaludate.defaultFileList = model.evaludate.evaluationReport;
//         model.evaludate.defaultFileList.forEach(el => {
//           el["name"] = el.fileName;
//         });
//       }
//     }

//     const res3 = await api.postAlterationList({ projectManageId: id });
//     if (res3.code === 200 && res3.data.list.length > 0) {
//       model.changeFormData = res3.data.list[0];
//     }
//   }
// };

const changeHandleder = async item => {
  model.selectProject = model.projectList.find(el => el.id === item);
  model.formData.projectName = model.selectProject.projectName;
  // await getProjectFroms(projectObj.id);
};

const changeeRviewStage = item => {
  model.formData.reviewStageName = item.dicValue;
};

const getProjectStages = async () => {
  try {
    const params = {
      dicType: "rd_rvw_pro_stage"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      projectStages.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};
const getExpertCategory = async () => {
  try {
    const params = {
      dicType: "rd_expert_category"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      expertCategoryList.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

const getProjectRound = async () => {
  try {
    const params = {
      dicType: "rd_rvw_round"
    };
    const { code, data } = await postDictList(params);
    if (code === 200) {
      projectRounds.value = data;
    }
  } catch (err) {
    console.log(err);
  }
};

const handleBack = () => {
  router.replace("/project/expert");
};

const goBack = (): void => {
  router.push("/project/expert");
};

const handleSubmit = async () => {
  model.formData.reviewSaveStatus = "2";
  model.formData.reviewApproveStatus = "1";
  const flag = await handleSave(false);
  if (flag === true) return;
  if (route.query.instanceId) {
    flowPassSubmit();
  } else {
    flowSumbitStart();
  }
};
const flowSumbitStart = async () => {
  flowStartData.formBaseInfo.billName =
    model.formData.projectName + "专家审批流程";
  flowStartData.formBaseInfo.projectName = model.formData.projectName;
  flowStartData.formBaseInfo.projectManageId = model.formData.projectManageId;
  flowStartData.flowFormData.projectManageId = model.formData.projectManageId;
  // flowStartData.flowFormData.businessId = route.query.id;
  const reviewExpert = authorSelectTable.value.participantList;
  const assignee = reviewExpert.map(el => el.userId);
  flowStartData.formSubMap.assignee = assignee.join(",");

  const { code, message } = await flowStart(flowStartData);
  if (code === 200) {
    model.saveLoading = false;
    NotifMessage.success(message);
    goBack();
  } else {
    model.saveLoading = false;
    model.centerDialogVisible = false;
    NotifMessage.error(message);
  }
};

const handleSave = async (isBack = true): Promise<any> => {
  const reviewExpert = authorSelectTable.value.participantList;

  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  const filter = reviewExpert.filter(el => el.opinion);
  if (isValid && filter.length === reviewExpert.length) {
    model.saveLoading = true;
    const copyFormData = cloneDeep(model.formData);
    copyFormData.reviewRoundCode = model.formData.reviewRoundCode.dicCode;
    copyFormData.reviewRoundName = model.formData.reviewRoundCode.dicValue;
    copyFormData.reviewStageCode = model.formData.reviewStageCode.dicCode;
    copyFormData.reviewStageName = model.formData.reviewStageCode.dicValue;
    if (reviewExpert) {
      copyFormData.rvwUserList = reviewExpert.map(el => {
        return {
          deptCode: el.companyId || el.deptCode,
          deptName: el.companyName || el.deptName,
          expertCategoryCode: el.opinion.dicCode,
          expertCategoryName: el.opinion.dicValue,
          expertGroupCode: "",
          expertGroupName: el.ext1,
          expertId: el.id,
          userId: el.userId,
          userName: el.name
        };
      });
    }
    copyFormData.id = expertId;
    delete copyFormData.catchFroms;

    const { code, message, data } = expertId
      ? await saveExpert(copyFormData)
      : await addExpert(copyFormData);
    if (route.query.id) {
      flowStartData.flowFormData.businessId = route.query.id;
      flowStartData.formBaseInfo.id = route.query.id;
    } else {
      flowStartData.flowFormData.businessId = data;
      flowStartData.formBaseInfo.id = data;
    }
    if (code === 200 && isBack) {
      // flowFormData..businessId=data as any;
      model.saveLoading = false;
      NotifMessage.success(message);
      goBack();
    }
    if (code !== 200) {
      model.saveLoading = false;
      NotifMessage.error(message);
    }
  } else {
    model.saveLoading = false;
    model.centerDialogVisible = false;
    NotifMessage.warning("请补充必填信息后，再次操作！");
    return true;
  }
};

const getExpert = async () => {
  const { code, data } = await getExpertDetail({ id: expertId });
  if (code === 200) {
    model.selectProject = {
      id: data.projectManageId,
      projectName: data.projectName
    };
    // await getProjectFroms(data.projectManageId);
    model.formData = cloneDeep(data);
    if (!model.formData.rvwUserList) {
      model.formData.rvwUserList = [];
    }
    model.formData.reviewRoundCode = {
      dicCode: data.reviewRoundCode,
      dicValue: data.reviewRoundName
    };
    model.formData.reviewStageCode = {
      dicCode: data.reviewStageCode,
      dicValue: data.reviewStageName
    };
    model.formData.rvwUserList.map(el => {
      el["name"] = el.userName;
      el["ext1"] = el.expertGroupName;
      el["companyName"] = el.deptName;
      el["opinion"] = {
        dicCode: el.expertCategoryCode,
        dicValue: el.expertCategoryName
      };
    });
  }
};
const isApproval =
  route.query.mode === "approval" || route.query.mode === "look" ? true : false;
model.flowType = route.query.flowType || "3009"
// initProjectInfo();
getProjectList();
initPslcList();
getProjectStages();
getProjectRound();
getExpertCategory();
if (expertId) {
  getExpert();
}
</script>

<style lang="scss" scoped>
.empt-content {
  height: calc(100vh - 200px);
  width: 100%;
}

.card-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-box-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-btn {
    font-size: 14px;
    cursor: pointer;
  }
}
</style>
